import { Sprite, Texture } from 'pixi.js';
import { Body } from 'matter-js';
import { Entity, EntityConfig } from './Entity';
import { Enemy } from './Enemy';

export interface BulletConfig extends EntityConfig {
  damage?: number;
  speed?: number;
  lifeTime?: number;
  direction: { x: number; y: number };
}

export class Bullet extends Entity {
  private damage: number;
  private speed: number;
  private lifeTime: number;
  private direction: { x: number; y: number };
  private elapsedTime: number;

  constructor(config: BulletConfig) {
    super(config);
    
    // 初始化子弹属性
    this.damage = config.damage || 20;
    this.speed = config.speed || 10;
    this.lifeTime = config.lifeTime || 2000; // 默认2秒后消失
    this.direction = config.direction;
    this.elapsedTime = 0;
    
    // 归一化方向向量
    const length = Math.sqrt(this.direction.x * this.direction.x + this.direction.y * this.direction.y);
    this.direction.x /= length;
    this.direction.y /= length;
    
    // 添加子弹标签
    this.addTag('bullet');
  }

  // 更新子弹状态
  public update(delta: number): void {
    // 更新生命时间
    this.elapsedTime += delta;
    if (this.elapsedTime >= this.lifeTime) {
      this.deactivate();
      return;
    }

    // 更新位置
    const newX = this.x + this.direction.x * this.speed;
    const newY = this.y + this.direction.y * this.speed;
    this.setPosition(newX, newY);

    // 设置旋转角度（使子弹朝向移动方向）
    const angle = Math.atan2(this.direction.y, this.direction.x);
    this.setRotation(angle);
  }

  // 处理碰撞
  public onCollision(other: Entity): void {
    if (other.hasTag('enemy')) {
      const enemy = other as Enemy;
      enemy.takeDamage(this.damage);
      this.deactivate(); // 子弹命中后消失
    } else if (other.hasTag('obstacle')) {
      this.deactivate(); // 子弹击中障碍物后消失
    }
  }

  // 获取伤害值
  public getDamage(): number {
    return this.damage;
  }

  // 销毁实例
  public destroy(): void {
    if (this.sprite && !this.sprite.destroyed) {
      this.sprite.destroy();
    }
    if (this.body && this.body.world) {
      World.remove(this.body.world, this.body);
    }
  }
}